package com.snakegame.service;

import com.snakegame.dto.GameResultRequest;
import com.snakegame.entity.GameRecord;
import com.snakegame.entity.User;
import com.snakegame.repository.GameRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GameRecordService {

    @Autowired
    private GameRecordRepository gameRecordRepository;

    @Autowired
    private UserService userService;

    public GameRecord saveGameResult(String username, GameResultRequest gameResultRequest) {
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 更新用户的最高分
        userService.updateHighestScore(username, gameResultRequest.getScore());

        GameRecord gameRecord = new GameRecord();
        gameRecord.setUser(user);
        gameRecord.setScore(gameResultRequest.getScore());
        gameRecord.setDurationSeconds(gameResultRequest.getDurationSeconds());
        gameRecord.setLevelReached(gameResultRequest.getLevelReached());

        return gameRecordRepository.save(gameRecord);
    }

    public List<GameRecord> getUserGameRecords(String username) {
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return gameRecordRepository.findByUserOrderByCreatedAtDesc(user);
    }

    public List<GameRecord> getTopScores() {
        return gameRecordRepository.findTop10ByOrderByScoreDesc();
    }

    public List<GameRecord> getUserBestScores(String username) {
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return gameRecordRepository.findBestScoresByUser(user);
    }
}